package com.study.www.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 多数据源：数据源1
 * @author : 89007337.zhuyanpeng
 **/
@Configuration
public class Test1DataSourceConfig {

    public static final String TEST1SQLSESSIONFACTORY="test1SqlSessionFactory";

    /**
     * 数据源
     */
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.test1")
    public DataSource test1DataSource(){
        return DruidDataSourceBuilder.create().build();
    }


    /**
    *  SqlSession 工厂
    */
    @Bean(TEST1SQLSESSIONFACTORY)
    @Primary
    public SqlSessionFactory test1SqlSessionFactory(@Value("${mybatis.test1.mapperLocations}")  String test1MapperLocations,
                                                    @Value("${mybatis.test1.type-aliases-package}")  String test1TypeAliasesPackage,
                                                   @Qualifier("test1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        //Mapper.xml 映射路径
        sqlSessionFactoryBean.setMapperLocations( new PathMatchingResourcePatternResolver()
                .getResources(test1MapperLocations));
        //package 映射路径
        sqlSessionFactoryBean.setTypeAliasesPackage(test1TypeAliasesPackage);
        //mybatis Config 配置
        ClassPathResource classPathResource = new ClassPathResource("mybatis-config.xml");
        sqlSessionFactoryBean.setConfigLocation(classPathResource);
        return sqlSessionFactoryBean.getObject();
    }

}
